package com.tianji.learning.utils;

import lombok.Data;

import java.io.Serializable;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: DelayTask
 * Package: com.tianji.learning.domain.delay
 * Description:
 *
 * @Author 陈宽
 * @Create 2025/6/30 14:46
 */
@Data
public class DelayTask<D> implements Delayed, Serializable {
    private long deadlineNanos;//延时执行时间的纳秒值
    private D data;//延时执行的数据

    public DelayTask(Duration duration, D data) {
        this.deadlineNanos = System.nanoTime()+duration.toNanos();
        this.data = data;
    }

    /**
     * 用来获取队列中每个任务距离当前时间还有多久被执行的时间
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadlineNanos-System.nanoTime(),0),TimeUnit.NANOSECONDS);
    }

    /**
     * 延时任务队列中的任务进行排序（排序依据：根据getDelay方法获取的任务延时时间进行排序，值越小
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long diff = getDelay(TimeUnit.NANOSECONDS)-o.getDelay(TimeUnit.NANOSECONDS);
        return diff > 0 ? 1 : diff == 0 ? 0 : -1;
    }
}
